/*
 * SummerSoft  YueYue-Travel Platform
 * <p>
 * Copyright (c) 2017-2018  SummerSoft Technology (Xiamen) Co.,LTD
 * All rights reserved.
 * <p>
 * This software is the confidential and proprietary information of SummerSoft
 * ("Confidential Information"). You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the
 * license agreement you entered into with SummerSoft.
 * <p>
 */

package com.yungu.swift.order.thread.driver.status;


import com.yungu.swift.assets.driver.model.dto.DriverDto;
import com.yungu.swift.assets.driver.model.dto.DriverStatusCycleDto;
import com.yungu.swift.assets.driver.service.DriverService;
import com.yungu.swift.assets.driver.service.DriverStatusCycleService;
import com.yungu.swift.base.SpringContextHolder;
import com.yungu.swift.constants.DriverConstant;
import com.yungu.swift.lbs.model.DriverLocation;
import com.yungu.swift.lbs.service.LocationService;
import com.yungu.swift.order.dao.OrderMapper;
import com.yungu.swift.utils.DateUtils;
import com.yungu.swift.utils.MapUtils;
import com.yungu.swift.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 司机状态周期记录操作类
 *
 * @author zouyiyu
 * @version 1.0
 * @date 2018/12/24 10:00
 */
@Slf4j
public class DriverStatusCycleRunnable implements Runnable {
    private static final String IS_EXCEPTION = "isException";
    // 5分钟
    private static final long OFF_LINE_TIME = 300;

    private DriverStatusCycleService driverStatusCycleService;
    private LocationService locationService;

    /**
     * 以下为需要插入到表中的字段
     */
    private String appid;
    private String driverUuid;
    private String orderUuid;
    private String carUuid;
    //操作动作
    private int action;

    //从外面传入的里程
    private Double paramMileage;

    public DriverStatusCycleRunnable(DriverStatusCycleService driverStatusCycleService, LocationService locationService, String appid, String driverUuid, String orderUuid, String carUuid, int action) {
        this.driverStatusCycleService = driverStatusCycleService;
        this.locationService = locationService;
        this.appid = appid;
        this.driverUuid = driverUuid;
        this.orderUuid = orderUuid;
        this.carUuid = carUuid;
        this.action = action;
    }

    public DriverStatusCycleRunnable(DriverStatusCycleService driverStatusCycleService, LocationService locationService, String appid, String driverUuid, String orderUuid, String carUuid, int action, Double paramMileage) {
        this.driverStatusCycleService = driverStatusCycleService;
        this.locationService = locationService;
        this.appid = appid;
        this.driverUuid = driverUuid;
        this.orderUuid = orderUuid;
        this.carUuid = carUuid;
        this.action = action;
        this.paramMileage = paramMileage;
    }

    @Override
    public void run() {
        try {
            if (StringUtils.isNotBlank(appid) && StringUtils.isNotBlank(driverUuid) && StringUtils.isNotBlank(carUuid)) {
                //下一个状态
                int status = 0;
                //当前统计状态
                int statsStatus = 0;
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                // 收车
                //出车动作，记录收车，新建空驶
                if (DriverStatusCycleDto.ACTION_ON_WORK == action) {
                    statsStatus = DriverStatusCycleDto.OFF_WORK;
                    status = DriverStatusCycleDto.EMPTY_RIDE;
                }
                // 空驶
                //出发动作，记录空驶，新建空载
                else if (DriverStatusCycleDto.ACTION_LEAVE == action) {
                    statsStatus = DriverStatusCycleDto.EMPTY_RIDE;
                    status = DriverStatusCycleDto.EMPTY_CARRY;
                }
                // 空载
                //上车动作，记录空载，新建服务
                else if (DriverStatusCycleDto.ACTION_RIDE == action) {
                    statsStatus = DriverStatusCycleDto.EMPTY_CARRY;
                    status = DriverStatusCycleDto.SERVICE;
                }
                // 服务
                //服务结束动作，记录服务，新建空驶
                else if (DriverStatusCycleDto.ACTION_SERVICE_OVER == action) {
                    statsStatus = DriverStatusCycleDto.SERVICE;
                    status = DriverStatusCycleDto.EMPTY_RIDE;
                }
                // 空驶
                //收车动作，记录空驶，新建下班
                else if (DriverStatusCycleDto.ACTION_OFF_WORK == action) {
                    statsStatus = DriverStatusCycleDto.EMPTY_RIDE;
                    status = DriverStatusCycleDto.OFF_WORK;
                }
                // 离线
                //离线动作，记录空驶，新建离线
                else if (DriverStatusCycleDto.ACTION_OFF_LINE == action) {
                    statsStatus = DriverStatusCycleDto.EMPTY_RIDE;
                    status = DriverStatusCycleDto.OFF_LINE;
                }
                // 空驶
                //在线动作，记录离线，新建空驶
                else if (DriverStatusCycleDto.ACTION_ON_LINE == action) {
                    statsStatus = DriverStatusCycleDto.OFF_LINE;
                    status = DriverStatusCycleDto.EMPTY_RIDE;
                }
                // 空驶（跨天分割）
                //分割动作，记录空驶，新建空驶
                else if (DriverStatusCycleDto.ACTION_SPLIT == action) {
                    statsStatus = DriverStatusCycleDto.EMPTY_RIDE;
                    status = DriverStatusCycleDto.EMPTY_RIDE;
                }
                // 空载（订单取消）
                //取消动作，记录空载，新建空驶
                else if (DriverStatusCycleDto.ACTION_CANCEL == action) {
                    statsStatus = DriverStatusCycleDto.EMPTY_CARRY;
                    status = DriverStatusCycleDto.EMPTY_RIDE;
                }

                if (DriverStatusCycleDto.ACTION_SERVICE_OVER == action || DriverStatusCycleDto.ACTION_CANCEL == action) {
                    //下班（司机未上班）
                    DriverService driverService = (DriverService) SpringContextHolder.getBean("driverService");
                    DriverDto driverDto = driverService.get(driverUuid).getData();
                    if (null != driverDto && DriverConstant.DRIVER_IS_NOT_WORK.equals(driverDto.getIsWork())) {
                        status = DriverStatusCycleDto.OFF_WORK;
                    }
                }

                Map<String, Object> params = MapUtils.build();
                params.put("driverUuid", driverUuid);
                params.put("active", DriverStatusCycleDto.ACTIVE_OFF);
                //自动分割动作和手动状态变更冲突时
                if (DriverStatusCycleDto.ACTION_SPLIT == action) {
                    //空驶状态
                    params.put("status", DriverStatusCycleDto.EMPTY_RIDE);
                }
                DriverStatusCycleDto driverStatusCycleDtoActive = driverStatusCycleService.queryOne(params).getData();
                if (null != driverStatusCycleDtoActive) {
                    double mileage = 0;
                    Map<String, Object> objectMap = locationService.getTodayLocationsByStatsStatus(driverUuid, statsStatus, orderUuid, driverStatusCycleDtoActive.getStartTime()).getData();
                    if (null != objectMap) {
                        //如果不存在异常
                        if (!objectMap.containsKey(IS_EXCEPTION)) {
                            List<DriverLocation> driverLocationList = (List<DriverLocation>) objectMap.get("locationList");
                            //初始日期为今天
                            Date today = new Date();
                            for (DriverLocation driverLocation : driverLocationList) {
                                //空驶
                                if (DriverStatusCycleDto.EMPTY_RIDE == driverStatusCycleDtoActive.getStatus()) {
                                    //跨天分割动作
                                    if (DriverStatusCycleDto.ACTION_SPLIT == action) {
                                        //日期不等于初始日期
                                        if (!DateUtils.isSameDay(today, driverLocation.getUploadTime())) {
                                            //里程累计
                                            mileage += driverLocation.getDistance();
                                        }
                                    } else {
                                        //日期等于初始日期
                                        if (DateUtils.isSameDay(today, driverLocation.getUploadTime())) {
                                            //里程累计
                                            mileage += driverLocation.getDistance();
                                        }
                                    }
                                    //不是空驶的情况
                                } else {
                                    //里程累计
                                    mileage += driverLocation.getDistance();
                                }

                            }

                            Date now = new Date();
                            if (DriverStatusCycleDto.ACTION_SPLIT == action) {
                                now = sdf.parse(sdf.format(now));
                            }
                            if (DriverStatusCycleDto.OFF_WORK != driverStatusCycleDtoActive.getStatus()) {
                                DecimalFormat df = new DecimalFormat("#.00");
                                driverStatusCycleDtoActive.setMileage(Double.parseDouble(df.format(mileage)));
                                //这边获取一下高德纠偏里程，存入新字段
                                if (paramMileage == null) {
                                    double trackMileage = locationService.getDrivingDistance(driverUuid,
                                            driverStatusCycleDtoActive.getStartTime().getTime(),
                                            System.currentTimeMillis()).getData() / 1000;
                                    log.info("通过高德车辆轨迹查询接口获取里程，trackMileage=" + trackMileage);
                                    driverStatusCycleDtoActive.setTrackMileage(trackMileage);
                                } else {
                                    driverStatusCycleDtoActive.setTrackMileage(paramMileage);
                                }
                            }
                            //时间差
                            long tdoa = 0;
                            long statusTime = (now.getTime() - driverStatusCycleDtoActive.getStartTime().getTime()) / 1000;
                            //离线定时器时间补偿
                            if (DriverStatusCycleDto.OFF_LINE == driverStatusCycleDtoActive.getStatus()) {
                                //初始为离线阀值
                                tdoa = OFF_LINE_TIME;
                                //获取上一个状态对象
                                DriverStatusCycleDto prveStatusDto = driverStatusCycleService.queryById(driverStatusCycleDtoActive.getPrevStatusUuid()).getData();
                                if (null != prveStatusDto) {
                                    long prveTime = (prveStatusDto.getEndTime().getTime() - prveStatusDto.getStartTime().getTime()) / 1000;
                                    //上一个状态时长小于离线阀值
                                    if (prveTime < OFF_LINE_TIME) {
                                        tdoa = prveTime;
                                    }
                                }
                            }
                            //离线前的时间补偿
                            if (DriverStatusCycleDto.ACTION_OFF_LINE == action && statusTime > OFF_LINE_TIME) {
                                tdoa = -1 * OFF_LINE_TIME;
                            }
                            driverStatusCycleDtoActive.setStatusTime((int) (statusTime + tdoa));
                            driverStatusCycleDtoActive.setActive(DriverStatusCycleDto.ACTIVE_ON);
                            driverStatusCycleDtoActive.setEndTime(now);
                            driverStatusCycleDtoActive.setUpdateBy(driverUuid);
                            driverStatusCycleDtoActive.setUpdateOn(now);
                            driverStatusCycleService.edit(driverStatusCycleDtoActive);
                        }
                    }
                }
                //是否初始化下一个状态（默认初始化）
                boolean isCreate = true;
                //自动分割动作和手动状态变更冲突时
                if (DriverStatusCycleDto.ACTION_SPLIT == action && null == driverStatusCycleDtoActive) {
                    isCreate = false;
                }

                if (isCreate) {
                    //初始化下一个状态数据-开始
                    Date now = new Date();
                    DriverStatusCycleDto driverStatusCycleDto = new DriverStatusCycleDto();
                    driverStatusCycleDto.setUuid(StringUtils.buildUUID());
                    driverStatusCycleDto.setAppid(appid);
                    driverStatusCycleDto.setCreateBy(driverUuid);
                    driverStatusCycleDto.setCreateOn(now);
                    driverStatusCycleDto.setRecordDate(now);
                    driverStatusCycleDto.setDriverUuid(driverUuid);
                    driverStatusCycleDto.setCurrentOrderUuid(orderUuid);
                    // 前一个订单号
                    OrderMapper orderMapper = (OrderMapper) SpringContextHolder.getBean("orderMapper");
                    driverStatusCycleDto.setPrevOrderUuid(orderMapper.getTodayPrevOrderUuid(driverUuid));
                    // 车辆id 从司机表中取
                    driverStatusCycleDto.setCarUuid(carUuid);
                    driverStatusCycleDto.setMileage(0.0);
                    driverStatusCycleDto.setTrackMileage(0.0);
                    driverStatusCycleDto.setStatusTime(0);
                    if (DriverStatusCycleDto.ACTION_SPLIT == action) {
                        driverStatusCycleDto.setStartTime(sdf.parse(sdf.format(now)));
                    } else {
                        driverStatusCycleDto.setStartTime(now);
                    }
                    //默认未激活
                    driverStatusCycleDto.setActive(DriverStatusCycleDto.ACTIVE_OFF);
                    //动作存储
                    driverStatusCycleDto.setAction(action);
                    //状态存储
                    driverStatusCycleDto.setStatus(status);
                    if (null != driverStatusCycleDtoActive) {
                        driverStatusCycleDto.setPrevStatusUuid(driverStatusCycleDtoActive.getUuid());
                    }
                    params.clear();
                    params.put("driverUuid", driverUuid);
                    params.put("recordDate", DateUtils.format(new Date(), "yyyy-MM-dd"));
                    Integer maxSort = driverStatusCycleService.getTodayMaxSort(params).getData();
                    if (maxSort == null) {
                        maxSort = 0;
                    }
                    // 司机当天的统计里程排序
                    driverStatusCycleDto.setSort(maxSort + 1);
                    driverStatusCycleService.add(driverStatusCycleDto);
                    //初始化下一个状态数据-结束
                }
            } else {
                log.error("司机状态记录日志：动作类型=" + action + "，APPID=" + appid + "，司机ID=" + driverUuid + "，车辆ID=" + carUuid + "，订单ID=" + orderUuid);
            }
        } catch (Exception e) {
            log.error("状态周期记录失败:", e);
            e.printStackTrace();
        }
    }
}
